import { useEffect, useState } from "react";
import {
  Card,
  Spin,
  Row,
  Col,
  Statistic,
  Typography,
  Space,
  Tag,
  Button,
} from "antd";
import ReactECharts from "echarts-for-react";
import {
  EyeOutlined,
  FileTextOutlined,
  UserOutlined,
  BarChartOutlined,
  CloudOutlined,
  DashboardOutlined,
  RiseOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import {
  fetchTop10Articles,
  fetchWordCloudUrl,
  fetchStatistics,
  fetchArticleCountByCategory,
  fetchMonthlyPublishCount,
} from "../api/stats";
import { isAdmin } from "../utils/auth";
import { useTheme } from "../contexts/ThemeContext";

const { Title, Text } = Typography;

export default function Stats() {
  const { isDarkMode } = useTheme();

  const [topArticles, setTopArticles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false); // 只用于刷新按钮的加载状态
  const [wordCloudUrl, setWordCloudUrl] = useState("");
  const [categoryData, setCategoryData] = useState([]);
  const [monthlyData, setMonthlyData] = useState([]);
  const [overallStats, setOverallStats] = useState({
    totalViews: 0,
    totalArticles: 0,
    totalUsers: 0,
    avgViews: 0,
  });

  // 加载统计数据
  const loadStats = (isRefresh = false) => {
    console.log("开始加载统计数据，刷新模式:", isRefresh);

    // 如果是刷新操作，只设置 refreshing 状态；如果是初始加载，设置 loading 状态
    if (isRefresh) {
      setRefreshing(true);
    }

    // 使用 Promise.all 等待所有数据加载完成
    Promise.all([
      fetchStatistics()
        .then((stats) => {
          console.log("统计数据加载成功:", stats);
          setOverallStats(stats);
          return stats;
        })
        .catch((err) => {
          console.error("加载统计数据失败:", err);
          setOverallStats({
            totalViews: 0,
            totalArticles: 0,
            totalUsers: 0,
            avgViews: 0,
          });
          return null;
        }),
      fetchTop10Articles()
        .then((articles) => {
          console.log("文章数据加载成功，共", articles.length, "篇:", articles);
          setTopArticles(articles);
          return articles;
        })
        .catch((err) => {
          console.error("加载文章数据失败:", err);
          setTopArticles([]);
          return null;
        }),
      fetchWordCloudUrl()
        .then((wordCloud) => {
          console.log("词云数据加载成功:", wordCloud);
          setWordCloudUrl(wordCloud);
          return wordCloud;
        })
        .catch((err) => {
          console.error("加载词云失败:", err);
          setWordCloudUrl("");
          return null;
        }),
      fetchArticleCountByCategory()
        .then((data) => {
          console.log("分类统计数据加载成功:", data);
          setCategoryData(Array.isArray(data) ? data : []);
          return data;
        })
        .catch((err) => {
          console.error("加载分类统计数据失败:", err);
          console.error("错误详情:", err.message || err);
          setCategoryData([]);
          return null;
        }),
      fetchMonthlyPublishCount()
        .then((data) => {
          console.log("月度发布数据加载成功:", data);
          setMonthlyData(Array.isArray(data) ? data : []);
          return data;
        })
        .catch((err) => {
          console.error("加载月度发布数据失败:", err);
          console.error("错误详情:", err.message || err);
          setMonthlyData([]);
          return null;
        }),
    ]).finally(() => {
      console.log("所有数据加载完成");
      if (isRefresh) {
        setRefreshing(false);
      }
    });
  };

  useEffect(() => {
    loadStats(false); // 初始加载，不设置loading状态
  }, []);

  // 监视数据变化
  useEffect(() => {
    console.log("topArticles 更新:", topArticles);
  }, [topArticles]);

  useEffect(() => {
    console.log("overallStats 更新:", overallStats);
  }, [overallStats]);

  useEffect(() => {
    console.log("wordCloudUrl 更新:", wordCloudUrl);
  }, [wordCloudUrl]);

  useEffect(() => {
    console.log("categoryData 更新:", categoryData);
  }, [categoryData]);

  useEffect(() => {
    console.log("monthlyData 更新:", monthlyData);
  }, [monthlyData]);

  // ECharts 柱状图配置
  const getBarChartOption = () => {
    // 按用户名分组数据
    const userGroups = {};
    topArticles.forEach((article) => {
      if (!userGroups[article.username]) {
        userGroups[article.username] = [];
      }
      userGroups[article.username].push(article);
    });

    // 生成用户颜色映射 - 使用渐变色彩方案
    const userColors = {};
    const colors = [
      "#1890ff", // 蓝色
      "#f5222d", // 红色
      "#52c41a", // 绿色
      "#fa8c16", // 橙色
      "#722ed1", // 紫色
      "#eb2f96", // 粉色
      "#13c2c2", // 青色
      "#faad14", // 金色
      "#2f54eb", // 深蓝
      "#fa541c", // 深橙
      "#096dd9", // 中蓝
      "#389e0d", // 深绿
      "#d46b08", // 深橙黄
      "#531dab", // 深紫
      "#c41d7f", // 深粉
    ];
    let colorIndex = 0;
    Object.keys(userGroups).forEach((username) => {
      userColors[username] = colors[colorIndex % colors.length];
      colorIndex++;
    });

    return {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: function (params) {
          const dataIndex = params[0].dataIndex;
          const article = topArticles.slice().reverse()[dataIndex];
          const userColor = userColors[article.username] || "#1890ff";
          return `
            <div style="padding: 12px; border-radius: 6px;">
              <div style="font-weight: bold; margin-bottom: 6px; color: ${
                isDarkMode ? "#fff" : "#333"
              }; font-size: 14px;">${article.title}</div>
              <div style="color: ${
                isDarkMode ? "#aaa" : "#666"
              }; font-size: 12px; margin-bottom: 6px;">
                <span style="display: inline-block; width: 8px; height: 8px; background: ${userColor}; border-radius: 50%; margin-right: 6px;"></span>
                作者: ${article.username}
              </div>
              <div style="color: ${userColor}; font-weight: bold; font-size: 14px;">阅读量: ${article.views.toLocaleString()}</div>
            </div>
          `;
        },
        backgroundColor: isDarkMode ? "#2d2d2d" : "#fff",
        borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        textStyle: {
          color: isDarkMode ? "#fff" : "#333",
        },
      },
      legend: {
        data: Object.keys(userGroups),
        bottom: 0,
        itemGap: 15,
        textStyle: {
          fontSize: 12,
          color: isDarkMode ? "#fff" : "#333",
        },
        orient: "horizontal",
      },
      grid: {
        left: "1%",
        right: "5%",
        bottom: "25%",
        top: "5%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        name: "阅读量",
        nameLocation: "middle",
        nameGap: 25,
        nameTextStyle: {
          fontSize: 12,
          color: isDarkMode ? "#aaa" : "#666",
        },
        axisLine: {
          lineStyle: {
            color: isDarkMode ? "#434343" : "#ddd",
          },
        },
        axisLabel: {
          color: isDarkMode ? "#aaa" : "#666",
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: isDarkMode ? "#3a3a3a" : "#f0f0f0",
            type: "dashed",
            width: 1,
          },
        },
      },
      yAxis: {
        type: "category",
        data: topArticles
          .slice()
          .reverse()
          .map((item) => item.title),
        axisLabel: {
          fontSize: 11,
          width: 120,
          overflow: "truncate",
          color: isDarkMode ? "#aaa" : "#333",
        },
        axisLine: {
          lineStyle: {
            color: isDarkMode ? "#434343" : "#ddd",
          },
        },
      },
      series: Object.keys(userGroups).map((username, index) => ({
        name: username,
        type: "bar",
        data: topArticles
          .slice()
          .reverse()
          .map((article) =>
            article.username === username ? article.views : 0
          ),
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: userColors[username], // 起始颜色
              },
              {
                offset: 1,
                color: userColors[username] + "80", // 结束颜色（添加透明度）
              },
            ],
          },
          borderRadius: [0, 4, 4, 0], // 右侧圆角
          shadowColor: userColors[username] + "40",
          shadowBlur: 8,
          shadowOffsetX: 2,
          shadowOffsetY: 2,
        },
        emphasis: {
          itemStyle: {
            color: userColors[username],
            shadowColor: userColors[username] + "60",
            shadowBlur: 12,
          },
        },
        barMaxWidth: 25,
        barGap: "10%",
      })),
    };
  };

  // ECharts 饼图配置 - 按分类统计文章
  const getPieChartOption = () => {
    // 显示所有分类，包括数量为0的分类
    const pieData = categoryData.map((item) => ({
      value: item.article_count,
      name: item.category_name,
    }));

    const colors = [
      "#1890ff",
      "#f5222d",
      "#52c41a",
      "#fa8c16",
      "#722ed1",
      "#eb2f96",
      "#13c2c2",
      "#faad14",
      "#2f54eb",
      "#fa541c",
    ];

    return {
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} 篇 ({d}%)",
        backgroundColor: isDarkMode ? "#2d2d2d" : "#fff",
        borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        textStyle: {
          color: isDarkMode ? "#fff" : "#333",
        },
      },
      legend: {
        orient: "vertical",
        right: "5%",
        top: "center",
        textStyle: {
          color: isDarkMode ? "#fff" : "#333",
          fontSize: 11,
        },
        itemGap: 8,
        itemWidth: 10,
        itemHeight: 10,
      },
      series: [
        {
          name: "文章数量",
          type: "pie",
          radius: ["30%", "70%"],
          center: ["40%", "50%"],
          data: pieData,
          itemStyle: {
            borderRadius: 3,
            borderColor: isDarkMode ? "#1f1f1f" : "#fff",
            borderWidth: 1,
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
          label: {
            show: true,
            formatter: "{b}\n{c}",
            color: isDarkMode ? "#fff" : "#333",
            fontSize: 10,
            distance: 8,
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 8,
          },
          color: colors,
        },
      ],
    };
  };

  // ECharts 折线图配置 - 按月度发布统计
  const getLineChartOption = () => {
    // 反转月度数据使其从远到近排列
    const sortedData = [...monthlyData].reverse();

    const months = sortedData.map((item) => item.year_month);
    const counts = sortedData.map((item) => item.count);

    return {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: isDarkMode ? "#2d2d2d" : "#fff",
          },
        },
        backgroundColor: isDarkMode ? "#2d2d2d" : "#fff",
        borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        textStyle: {
          color: isDarkMode ? "#fff" : "#333",
        },
      },
      grid: {
        left: "3%",
        right: "3%",
        bottom: "15%",
        top: "5%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: months,
        boundaryGap: false,
        axisLine: {
          lineStyle: {
            color: isDarkMode ? "#434343" : "#ddd",
          },
        },
        axisLabel: {
          color: isDarkMode ? "#aaa" : "#666",
          rotate: 45,
          fontSize: 11,
        },
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        type: "value",
        name: "发布数量",
        nameTextStyle: {
          color: isDarkMode ? "#aaa" : "#666",
          fontSize: 12,
        },
        axisLine: {
          lineStyle: {
            color: isDarkMode ? "#434343" : "#ddd",
          },
        },
        axisLabel: {
          color: isDarkMode ? "#aaa" : "#666",
        },
        splitLine: {
          lineStyle: {
            color: isDarkMode ? "#3a3a3a" : "#f0f0f0",
            type: "dashed",
          },
        },
      },
      series: [
        {
          name: "发布数量",
          type: "line",
          data: counts,
          smooth: true,
          itemStyle: {
            color: "#1890ff",
            borderWidth: 2,
          },
          lineStyle: {
            color: "#1890ff",
            width: 3,
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#1890ff80",
                },
                {
                  offset: 1,
                  color: "#1890ff00",
                },
              ],
            },
          },
          emphasis: {
            itemStyle: {
              borderWidth: 3,
              shadowColor: "#1890ff60",
              shadowBlur: 8,
            },
          },
          symbolSize: 6,
        },
      ],
    };
  };

  if (loading) {
    return (
      <div style={{ maxWidth: 1200, margin: "20px auto", textAlign: "center" }}>
        <Spin size="large" style={{ marginTop: 100 }} />
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
          <DashboardOutlined /> 数据统计分析
        </Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          基于 FastAPI 服务的智能数据分析与可视化
        </Text>
      </div>

      {/* 总体统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 32 }}>
        <Col xs={24} sm={12} md={6}>
          <Card
            size="small"
            style={{
              textAlign: "center",
              height: "100%",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              transition: "all 0.3s ease",
            }}>
            <EyeOutlined
              style={{ fontSize: 32, color: "#1890ff", marginBottom: 8 }}
            />
            <Statistic
              title="总阅读量"
              value={overallStats.totalViews}
              suffix="次"
              valueStyle={{ color: "#1890ff" }}
              loading={overallStats.totalViews === 0 && !refreshing}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card
            size="small"
            style={{
              textAlign: "center",
              height: "100%",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              transition: "all 0.3s ease",
            }}>
            <FileTextOutlined
              style={{ fontSize: 32, color: "#52c41a", marginBottom: 8 }}
            />
            <Statistic
              title="文章总数"
              value={overallStats.totalArticles}
              suffix="篇"
              valueStyle={{ color: "#52c41a" }}
              loading={overallStats.totalArticles === 0 && !refreshing}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card
            size="small"
            style={{
              textAlign: "center",
              height: "100%",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              transition: "all 0.3s ease",
            }}>
            <UserOutlined
              style={{ fontSize: 32, color: "#fa8c16", marginBottom: 8 }}
            />
            <Statistic
              title="活跃作者"
              value={overallStats.totalUsers}
              suffix="人"
              valueStyle={{ color: "#fa8c16" }}
              loading={overallStats.totalUsers === 0 && !refreshing}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card
            size="small"
            style={{
              textAlign: "center",
              height: "100%",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              transition: "all 0.3s ease",
            }}>
            <RiseOutlined
              style={{ fontSize: 32, color: "#722ed1", marginBottom: 8 }}
            />
            <Statistic
              title="平均阅读"
              value={overallStats.avgViews}
              suffix="次"
              precision={1}
              valueStyle={{ color: "#722ed1" }}
              loading={overallStats.avgViews === 0 && !refreshing}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]}>
        {/* 文章阅读排行榜 - 拉长两行 */}
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <BarChartOutlined style={{ color: "#1890ff" }} />
                <span>文章阅读排行榜</span>
              </Space>
            }
            extra={<Tag color="blue">TOP 10</Tag>}
            style={{
              borderRadius: 12,
              boxShadow: isDarkMode
                ? "0 2px 12px rgba(0,0,0,0.3)"
                : "0 2px 12px #eee",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              height: 676,
              transition: "all 0.3s ease",
            }}>
            {topArticles.length > 0 ? (
              <ReactECharts
                key={`chart-${topArticles.length}`}
                option={getBarChartOption()}
                notMerge={true}
                style={{ height: "550px", width: "100%" }}
              />
            ) : (
              <div
                style={{
                  height: "500px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: isDarkMode ? "#999" : "#ccc",
                  fontSize: 14,
                }}>
                <Spin /> 正在加载数据...
              </div>
            )}
          </Card>
        </Col>

        {/* 右侧上方：词云 + 饼图 合并 */}
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <CloudOutlined style={{ color: "#722ed1" }} />
                <span>搜索关键词词云</span>
              </Space>
            }
            extra={<Tag color="purple">生成</Tag>}
            style={{
              borderRadius: 12,
              boxShadow: isDarkMode
                ? "0 2px 12px rgba(0,0,0,0.3)"
                : "0 2px 12px #eee",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              textAlign: "center",
              height: 280,
              transition: "all 0.3s ease",
            }}>
            {wordCloudUrl ? (
              <div
                style={{
                  padding: "8px 0",
                  height: "100%",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                }}>
                <img
                  src={wordCloudUrl}
                  alt="搜索词云"
                  style={{
                    maxWidth: "90%",
                    height: "auto",
                    maxHeight: "180px",
                    borderRadius: 8,
                    boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                  }}
                />
              </div>
            ) : (
              <div
                style={{
                  padding: "40px 20px",
                  height: "100%",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                }}>
                <Spin style={{ marginBottom: 16 }} />
                <div style={{ color: "#999", fontSize: 12 }}>
                  正在加载词云数据...
                </div>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 第二行：排行榜（第二部分）+ 饼图 */}
      <Row gutter={[16, 16]} style={{ marginTop: -380 }}>
        <Col xs={24} lg={12}></Col>
        <Col xs={24} lg={12}>
          <Card
            title={
              <Space>
                <BarChartOutlined style={{ color: "#fa8c16" }} />
                <span>分类维度文章数分布</span>
              </Space>
            }
            extra={<Tag color="orange">分布</Tag>}
            style={{
              borderRadius: 12,
              boxShadow: isDarkMode
                ? "0 2px 12px rgba(0,0,0,0.3)"
                : "0 2px 12px #eee",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              height: 380,
              transition: "all 0.3s ease",
            }}>
            {categoryData.length > 0 ? (
              <ReactECharts
                key={`pie-chart-${categoryData.length}`}
                option={getPieChartOption()}
                notMerge={true}
                style={{ height: "280px", width: "100%" }}
              />
            ) : (
              <div
                style={{
                  height: "280px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: isDarkMode ? "#999" : "#ccc",
                  fontSize: 14,
                }}>
                <Spin /> 正在加载数据...
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 按月度发布统计 - 折线图 全宽 */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        <Col xs={24}>
          <Card
            title={
              <Space>
                <BarChartOutlined style={{ color: "#13c2c2" }} />
                <span>月度文章发布趋势图</span>
              </Space>
            }
            extra={<Tag color="cyan">趋势</Tag>}
            style={{
              borderRadius: 12,
              boxShadow: isDarkMode
                ? "0 2px 12px rgba(0,0,0,0.3)"
                : "0 2px 12px #eee",
              backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
              borderColor: isDarkMode ? "#434343" : "#d9d9d9",
              height: 420,
              transition: "all 0.3s ease",
            }}>
            {monthlyData.length > 0 ? (
              <ReactECharts
                key={`line-chart-${monthlyData.length}`}
                option={getLineChartOption()}
                notMerge={true}
                style={{ height: "320px", width: "100%" }}
              />
            ) : (
              <div
                style={{
                  height: "320px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: isDarkMode ? "#999" : "#ccc",
                  fontSize: 14,
                }}>
                <Spin /> 正在加载数据...
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
}
